﻿using System;
using System.Windows.Data;

namespace NamedBinaryTag.Converters
{
#if !SILVERLIGHT
	[ValueConversion(typeof(TagFile), typeof(byte))]
	[ValueConversion(typeof(TagFile), typeof(short))]
	[ValueConversion(typeof(TagFile), typeof(int))]
	[ValueConversion(typeof(TagFile), typeof(long))]
	[ValueConversion(typeof(TagFile), typeof(float))]
	[ValueConversion(typeof(TagFile), typeof(double))]
	[ValueConversion(typeof(TagFile), typeof(byte[]))]
	[ValueConversion(typeof(TagFile), typeof(string))]
	[ValueConversion(typeof(TagFile), typeof(System.Collections.ObjectModel.ObservableCollection<ITag>))]
#endif
	public class TagPathValueConverter : IValueConverter
	{
		protected const string MissingParameter = "Missing converter parameter.";
		#region IValueConverter Members

		public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
#if !SILVERLIGHT
			if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)
				return parameter == null ? MissingParameter : parameter;
#endif
			ITag tag = value as ITag;
			if (tag == null)
				return null;
			if (parameter as string == null)
				return null;
			PathWalker walker = new PathWalker(parameter as string);
			try
			{
				return walker.Walk(tag);
			}
			catch (Exception e)
			{
				throw new Exception("Exception in converter", e);
			}
		}

		public virtual object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			return null;
		}

		#endregion

		public object Default { get; set; }
	}
}
